 //
//  Network.m
//  UI18_AFN二次封装
//
//  Created by dllo on 15/8/31.
//  Copyright (c) 2015年 2015年 蓝鸥科技. All rights reserved.
//

#import "Network.h"
#import "Reachability.h"
#import <AFNetworking.h>
#import "HUDManager.h"

@implementation Network

+ (void)networkGETRequesWithURL:(NSString *)url
                       Paramater:(NSDictionary *)dic
       pageUniquenessIdentifier:(NSString *)pageUniquenessIdentifier
                          result:(void (^)(id))block
{
    // 转码
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    /* 开始缓存 */
    // 获取Caches路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    
    /*创建缓存文件*/
    NSString *LDYCachesFolderName = [NSString stringWithFormat:@"%@/LDYCaches",cachesPath];
    NSLog(@"%@", LDYCachesFolderName);
    NSFileManager *filemanger = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    BOOL existed = [filemanger fileExistsAtPath:LDYCachesFolderName isDirectory:&isDirectory];
    if (!(isDirectory == YES && existed == YES)) {
        [filemanger createDirectoryAtPath:LDYCachesFolderName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    /* 缓存文件名*/
    NSString *cachesFileString = [NSString stringWithFormat:@"resultDataCacheFile_%@.plist",pageUniquenessIdentifier];
    
    /* 拼接路径 */
    NSString *cacheExistPath = [LDYCachesFolderName stringByAppendingFormat:@"/%@",cachesFileString];
    NSLog(@"Caches: %@",cacheExistPath);
    /* 缓存创建文件名结束 */
    
    // 判断是否有网
    if ([self isNetworkConnectionAvailable]) {
        // 创建请求对象
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        // 请求HTTPS(若不添加, 无法解析HTTPS)
        manager.securityPolicy.allowInvalidCertificates = YES;
        // 设置请求格式
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        // 响应格式
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 设置响应的类型
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", nil]];
        
        [manager.requestSerializer setValue:@"application/json; application/x-javascript;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        // 加载指示器
//        [HUDManager showStatusWithString:@"加载中..."];
        
        // GET请求
        /**
         * 参数1: url
         * 参数2: 拼接的body
         * 参数3: 成功块
         * 参数4: 失败块
         */
        [manager GET:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 转成JSON
            // operation.responseObject请求回的数据(请求回来的真正二进制文件)
            id result = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:NSJSONReadingMutableContainers error:nil];
//            [HUDManager dismissHUD];
            
            /* 开始缓存 */
            [NSKeyedArchiver archiveRootObject:result toFile:cacheExistPath];
            /* 开始缓存 */
            
            block(result);
//            [HUDManager closeHUD];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 输出错误信息
            NSLog(@"%@", error);
        }];
        
    } else {
        
        /*  判断有网没网进行数据的缓存和缓存后的数据读取工作 */
        NSDictionary *takeOutCachesDataDic = [NSKeyedUnarchiver unarchiveObjectWithFile:cacheExistPath];
        if (takeOutCachesDataDic) {
            
            NSLog(@"无网 ----- 有缓存数据");
            block(takeOutCachesDataDic);
        }else
        {
            NSLog(@"无网 ----- 无缓存数据");
            /* 进行提示 */
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无网络连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
//        [HUDManager closeHUD];
    }
    
}

+ (void)networkPOSTRequestWithURL:(NSString *)url
                             body:(NSString *)body
         pageUniquenessIdentifier:(NSString *)pageUniquenessIdentifier
                           result:(void(^)(id result))block
{
    
    // 转码
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    /* 开始缓存 */
    // 获取Caches路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    
    /*创建缓存文件*/
    NSString *LDYCachesFolderName = [NSString stringWithFormat:@"%@/LDYCaches",cachesPath];
    NSLog(@"%@", LDYCachesFolderName);
    NSFileManager *filemanger = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    BOOL existed = [filemanger fileExistsAtPath:LDYCachesFolderName isDirectory:&isDirectory];
    if (!(isDirectory == YES && existed == YES)) {
        [filemanger createDirectoryAtPath:LDYCachesFolderName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    /* 缓存文件名*/
    NSString *cachesFileString = [NSString stringWithFormat:@"resultDataCacheFile_%@.plist",pageUniquenessIdentifier];
    
    /* 拼接路径 */
    NSString *cacheExistPath = [LDYCachesFolderName stringByAppendingFormat:@"/%@",cachesFileString];
    NSLog(@"Caches: %@",cacheExistPath);
    /* 缓存创建文件名结束 */
    
    if ([self isNetworkConnectionAvailable]) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.securityPolicy.allowInvalidCertificates = YES;
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", @"application/x-javascript",nil]];
//        [HUDManager showStatusWithString:@"加载中...."];
        
        NSArray *bodyArr = [body componentsSeparatedByString:@"&"];
        NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
        for (NSString *string in bodyArr) {
            NSArray *tempArr = [string componentsSeparatedByString:@"="];
            [bodyDic setObject:tempArr[1] forKey:tempArr[0]];
        }
        
        [manager POST:url parameters:bodyDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSLog(@"%@", responseObject);
            
            id result = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:NSJSONReadingMutableContainers error:nil];
            
            /* 开始缓存 */
            [NSKeyedArchiver archiveRootObject:result toFile:cacheExistPath];
            /* 开始缓存 */
                                    
//            [HUDManager closeHUD];
            block(result);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
    } else {
        
        /*  判断有网没网进行数据的缓存和缓存后的数据读取工作 */
        NSDictionary *takeOutCachesDataDic = [NSKeyedUnarchiver unarchiveObjectWithFile:cacheExistPath];
        if (takeOutCachesDataDic) {
            
            NSLog(@"无网 ----- 有缓存数据");
            block(takeOutCachesDataDic);
        }else
        {
            NSLog(@"无网 ----- 无缓存数据");
            /* 进行提示 */
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无网络连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
        //        [HUDManager closeHUD];
    }
}

+ (BOOL)isNetworkConnectionAvailable
{
    BOOL WithTheNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
        {
            WithTheNetwork = NO;
            NSLog(@"无网络连接");
        }
            break;
        case ReachableViaWiFi:
        {
            WithTheNetwork = YES;
            NSLog(@"通过WiFi连接");
        }
            break;
        case ReachableViaWWAN:
        {
            WithTheNetwork = YES;
            NSLog(@"通过GPRS网络连接");
        }
            break;
        default:
            break;
    }
    return WithTheNetwork;
}

@end
